package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.xiaoymin.knife4j.core.util.CollectionUtils;
import com.google.gson.JsonObject;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.properties.WeChatProperties;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.*;
import com.sky.websocket.WebSocketServer;
import com.sun.org.apache.bcel.internal.generic.NEW;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.spi.ObjectThreadContextMap;
import org.omg.CORBA.ORB;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.RejectedExecutionException;
import java.util.stream.Collectors;


/**
 * @Author: WangHongKun
 * @Date: 2022/9/22 16:58
 * @Email: 2028911483@qq.com
 * @Phone: 18683977706
 */

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Autowired
    private  AddressBookMapper addressBookMapper;

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private  DishMapper dishMapper;

    @Autowired
    private WeChatPayUtil weChatPayUtil;

    @Autowired
    private WeChatProperties weChatProperties;

    @Value("{sky.shop.address}")
    private String shopAddress;
    @Value("{sky.baidu.ak}")
    private String ak;


    @Autowired
    private WebSocketServer webSocketServer;

    @Override
    @Transactional
    public OrderSubmitVO submit(OrdersSubmitDTO ordersSubmitDTO)  {
        Long addressBookId = ordersSubmitDTO.getAddressBookId();
        AddressBook addressBook = addressBookMapper.getById(addressBookId);
        Long currentId = BaseContext.getCurrentId();
        //说明配送地址为空或者超出配送范围
        if(addressBook == null ){
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        //验证是否超出配送范围
//        checkAddressInCircle(addressBook.getCityName()+addressBook.getDistrictName()+addressBook.getDetail());

        //如果购物车为空也不能下单
        List<ShoppingCart> list = shoppingCartMapper.getList(currentId);
        if(list  ==null && list.size() ==0){
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        //如果满足以上条件 ，则执行submit 并且 清空购物车
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO,orders);
        orders.setUserId(currentId);
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(Orders.UN_PAID);
        orders.setStatus(Orders.PENDING_PAYMENT);
        User user = userMapper.getById(currentId);
        orders.setUserName(user.getName());
        orders.setPhone(addressBook.getPhone());
        orders.setAddress(addressBook.getDetail());
        orders.setConsignee(addressBook.getConsignee());
        orderMapper.insert(orders);

        List<OrderDetail>  orderDetailList = new ArrayList<>();
        //建立order_detail
        for(ShoppingCart shoppingCart:list){
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(shoppingCart,orderDetail);
            orderDetail.setOrderId(orders.getId());
            orderDetailList.add(orderDetail);
        }
        //批量插入
        orderDetailMapper.insertBatch(orderDetailList);
        //清空购物车
        shoppingCartMapper.clean(currentId);
        return OrderSubmitVO.builder()
                .id(orders.getId())
                .orderAmount(orders.getAmount())
                .orderNumber(orders.getNumber())
                .orderTime(orders.getOrderTime())
                .build();
    }

    @Override
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        Long currentId = BaseContext.getCurrentId();
        User user = userMapper.getById(currentId);
//        JSONObject jsonObject = weChatPayUtil.pay(
//                ordersPaymentDTO.getOrderNumber(), new BigDecimal(0.1)
//                , "西油外卖订单"
//                , user.getOpenid()
//        );
//        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
//            throw new OrderBusinessException("该订单已支付");
//        }
//        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
//        vo.setPackageStr(jsonObject.getString("package"));
        //模拟 微信支付
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", "ORDERPAID");

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        // 替代微信支付成功后的数据库订单状态更新，直接在这里更新了
        // 根据订单号查询当前用户的该订单
        Orders ordersDB = orderMapper.getByNumberAndUserId(ordersPaymentDTO.getOrderNumber(), currentId);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间

        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED) // 订单状态，待接单
                .payStatus(Orders.PAID) // 支付状态，已支付
                .checkoutTime(LocalDateTime.now()) // 更新支付时间
                .build();

        orderMapper.update(orders);
        HashMap<String, Object> map = new HashMap<>();
        map.put("type",1);
        map.put("orderId",orders.getId());
        map.put("content","订单号："+ ordersPaymentDTO.getOrderNumber());
        webSocketServer.sendToAllClient(JSONObject.toJSONString(map));
        return vo;
    }

    @Override
    public void  paySuccess(String number){
        Long currentId = BaseContext.getCurrentId();
        Orders ordersDB = orderMapper.getByNumberAndUserId(number, currentId);
        Orders orders =  Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.PENDING_PAYMENT)
                .checkoutTime(LocalDateTime.now())
                .payStatus(Orders.PAID)
                .build();
        orderMapper.update(orders);

        return;
    }

    @Override
    @Transactional
    public PageResult<OrderVO> historyOrders(OrdersPageQueryDTO ordersPageQueryDTO) {
        Orders orders = new Orders();
        Long currentId = BaseContext.getCurrentId();
        orders.setUserId(currentId);
        orders.setStatus(ordersPageQueryDTO.getStatus());
        //分页查询
        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());
        //分页
        Page<Orders> page = (Page<Orders>) orderMapper.getByUserIdAndStatus(orders);
        List<OrderVO> list = new ArrayList<>();
        if(page !=null && page.getTotal()>0){
            for(Orders orders1: page.getResult()){
                List<OrderDetail> orderDetailList = orderDetailMapper.getById(orders1.getId());
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders1,orderVO);
                orderVO.setOrderDetailList(orderDetailList);
                list.add(orderVO);
            }
        }
        return new PageResult<>(page.getTotal(),list);
    }

    @Override
    public OrderVO QueryOrderDetail(Long id) {
        Orders orders = orderMapper.getById(id);
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(id);
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders,orderVO);
        orderVO.setOrderDetailList(orderDetailList);
        return orderVO;
    }

    @Override
    public void CancelOrder(Long id) {
        orderMapper.cancel(id,Orders.CANCELLED);
    }

    @Transactional
    @Override
    public void repetition(Long id) {
        Orders orders = orderMapper.getById(id);
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(orders.getId());
        for (OrderDetail orderDetail:orderDetailList){
            ShoppingCart shoppingCart = ShoppingCart.builder()
                    .name(orderDetail.getName())
                    .userId(BaseContext.getCurrentId())
                    .dishId(orderDetail.getDishId())
                    .setmealId(orderDetail.getSetmealId())
                    .dishFlavor(orderDetail.getDishFlavor())
                    .number(orderDetail.getNumber())
                    .amount(orderDetail.getAmount())
                    .image(orderDetail.getImage())
                    .createTime(LocalDateTime.now())
                    .build();
            shoppingCartMapper.insert(shoppingCart);
        }
    }

    @Override
    @Transactional
    public PageResult<OrderVO> conditionSearch(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());
        Page<Orders> page = orderMapper.pageQuery(ordersPageQueryDTO);
        long total = page.getTotal();
        List<Orders> result = page.getResult();
        List<OrderVO> orderVOList  = new ArrayList<>();
        for(Orders orders: result){
            OrderVO orderVO = new OrderVO();
            BeanUtils.copyProperties(orders,orderVO);
            orderVOList.add(orderVO);
        }
        for(OrderVO orderVO : orderVOList){
            List<OrderDetail> byOrderId = orderDetailMapper.getByOrderId(orderVO.getId());
            orderVO.setOrderDetailList(byOrderId);
            orderVO.setOrderDishes(getOrderDishes(orderVO));
        }

        PageResult<OrderVO> pageResult = new PageResult<>();
        pageResult.setTotal(total);
        pageResult.setRecords(orderVOList);
        return pageResult;
    }

    public String getOrderDishes(OrderVO orderVO){
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(orderVO.getId());
        StringBuilder stringBuilder = new StringBuilder();
        for(OrderDetail orderDetail :orderDetailList){
            String name = orderDetail.getName();
            Integer number = orderDetail.getNumber();
            stringBuilder.append(name+'*'+number +";");
        }
        return stringBuilder.toString();
    }

    @Override
    public OrderStatisticsVO getStatistics(){
        return new OrderStatisticsVO(orderMapper.getStatusCount(Orders.TO_BE_CONFIRMED),
                orderMapper.getStatusCount(Orders.CONFIRMED),
                orderMapper.getStatusCount(Orders.DELIVERY_IN_PROGRESS));
    }

    @Override
    public OrderVO getOrderDetail(Long id) {
        Orders orders = orderMapper.getById(id);
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders,orderVO);
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(orderVO.getId());
        orderVO.setOrderDetailList(orderDetailList);
        orderVO.setOrderDishes(getOrderDishes(orderVO));
        return orderVO;
    }

    @Override
    public void confirmOrder(Long id) {
        orderMapper.setOrderStatus(id,Orders.CONFIRMED);
    }

    @Override
    public void rejection(Long id, String rejectionReason) {
        Orders orders = orderMapper.getById(id);
        //表示订单不存在或者订单状态有误
        if(orders == null || !orders.getStatus().equals(Orders.TO_BE_CONFIRMED)){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
//        //退款
//        try {
//            weChatPayUtil.refund(orders.getNumber()
//            ,orders.getNumber(),new BigDecimal(0.01),new BigDecimal(
//
//                    0.01));
//        } catch (Exception e) {
//            e.printStackTrace();
//        }

        Orders orders1 = Orders.builder()
                .id(id)
                .status(Orders.CANCELLED)
                .cancelTime(LocalDateTime.now())
                .rejectionReason(rejectionReason)
                .payStatus(Orders.REFUND)
                .build();
        orderMapper.update(orders1);
        return;
    }

    @Override
    public void cancel(OrdersCancelDTO ordersCancelDTO) {
        Orders orders = orderMapper.getById(ordersCancelDTO.getId());
        //表示订单不存在或者订单状态有误
        if(orders == null || orders.getStatus().equals(Orders.COMPLETED)|| orders.getStatus().equals(Orders.CANCELLED)|| orders.getStatus().equals(Orders.DELIVERY_IN_PROGRESS)){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
//        //退款
//        try {
//            weChatPayUtil.refund(orders.getNumber()
//            ,orders.getNumber(),new BigDecimal(0.01),new BigDecimal(
//
//                    0.01));
//        } catch (Exception e) {
//            e.printStackTrace();
//        }

        Orders orders1 = Orders.builder()
                .id(orders.getId())
                .status(Orders.CANCELLED)
                .cancelTime(LocalDateTime.now())
                .cancelReason(ordersCancelDTO.getCancelReason())
                .payStatus(Orders.REFUND)
                .build();
        orderMapper.update(orders1);
        return;
    }

    @Override
    public void delivery(Long id) {
        Orders orders = orderMapper.getById(id);
        //表示订单不存在或者订单状态有误
        if(orders == null || !orders.getStatus().equals(Orders.CONFIRMED)){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Orders orders1 = Orders.builder()
                .id(orders.getId())
                .status(Orders.DELIVERY_IN_PROGRESS)
                .build();
        orderMapper.update(orders1);
        return;
    }

    @Override
    public void complete(Long id) {
        Orders orders = orderMapper.getById(id);
        //表示订单不存在或者订单状态有误
        if(orders == null|| !orders.getStatus().equals(Orders.DELIVERY_IN_PROGRESS)){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Orders orders1 = Orders.builder()
                .id(orders.getId())
                .status(Orders.COMPLETED)
                .build();
        orderMapper.update(orders1);
        return;
    }

    @Override
    public void reminder(Long id) {
        Orders orders = orderMapper.getById(id);
        if(orders == null ){
            throw  new OrderBusinessException("订单不存在");
        }
        HashMap<String, Object> map = new HashMap<>();
        map.put("type",2);
        map.put("orderId",orders.getId());
        map.put("content","订单号：" + orders.getNumber());
        webSocketServer.sendToAllClient(JSONObject.toJSONString(map));
    }


    public void  checkAddressInCircle(String address){
        Map map = new HashMap<>();
        map.put("address",shopAddress);
        map.put("ak",ak);
        map.put("output","json");

        //获取当前商铺的经纬度
        String shopCoordinate = HttpClientUtil.doGet("https://api.map.baidu.com/geocoding/v3", map);
        JSONObject jsonObject = JSON.parseObject(shopCoordinate);
        if (jsonObject.getString("status").equals("0")) {
            throw new OrderBusinessException("商品地址解析失败");
        }
        //数据解析
        JSONObject location = jsonObject.getJSONObject("result").getJSONObject("location");
        String lat = location.getString("lat"); //纬度
        String lng = location.getString("lng"); //经度

        //商铺经纬度
        String shopLngLat =  lat +","+lng;
        map.put("address",address);


        //获取当前用户的经纬度
        String userCoordinate = HttpClientUtil.doGet("https://api.map.baidu.com/geocoding/v3", map);
        JSONObject jsonObject1 = JSON.parseObject(userCoordinate);
        if (jsonObject.getString("status").equals("0")) {
            throw new OrderBusinessException("用户地址解析失败");
        }


        //数据解析
        JSONObject location1 = jsonObject1.getJSONObject("result").getJSONObject("location");
        String lat1 = location1.getString("lat"); //纬度
        String lng1= location1.getString("lng"); //经度
        //收货地址经纬度
        String userLngLat =  lat1 + ","+ lng1;

        map.put("origin",shopLngLat);
        map.put("destination",userLngLat);
        map.put("steps_info","0");


        //规划路线
        String road = HttpClientUtil.doGet("https://api.map.baidu.com/directionlite/v1/driving", map);

        jsonObject = JSON.parseObject(road);
        if(!jsonObject.getString("status").equals("0")){
            throw new OrderBusinessException("配送路线规划失败");
        }

        //数据解析
        JSONObject result = jsonObject.getJSONObject("result");
        JSONArray jsonArray = (JSONArray) result.get("routes");
        Integer distance = (Integer) ((JSONObject) jsonArray.get(0)).get("distance");

        if(distance > 5000){
            //配送距离超过5000米
            throw new OrderBusinessException("超出配送范围");
        }

    }



}
